
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Serializing Django objects &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="Django settings" href="settings.html" />
    <link rel="prev" title="Performance and optimization" href="performance.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="performance.html" title="Performance and optimization">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="settings.html" title="Django settings">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-serialization">
            
  <div class="section" id="s-serializing-django-objects">
<span id="serializing-django-objects"></span><h1>Serializing Django objects<a class="headerlink" href="#serializing-django-objects" title="永久链接至标题">¶</a></h1>
<p>Django's serialization framework provides a mechanism for &quot;translating&quot; Django
models into other formats. Usually these other formats will be text-based and
used for sending Django data over a wire, but it's possible for a
serializer to handle any format (text-based or not).</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">If you just want to get some data from your tables into a serialized
form, you could use the <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">dumpdata</span></code></a> management command.</p>
</div>
<div class="section" id="s-serializing-data">
<span id="serializing-data"></span><h2>Serializing data<a class="headerlink" href="#serializing-data" title="永久链接至标题">¶</a></h2>
<p>At the highest level, you can serialize data like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">serializers</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s2">&quot;xml&quot;</span><span class="p">,</span> <span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
<p>The arguments to the <code class="docutils literal notranslate"><span class="pre">serialize</span></code> function are the format to serialize the data
to (see <a class="reference internal" href="#id2">Serialization formats</a>) and a
<a class="reference internal" href="../ref/models/querysets.html#django.db.models.query.QuerySet" title="django.db.models.query.QuerySet"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuerySet</span></code></a> to serialize. (Actually, the second
argument can be any iterator that yields Django model instances, but it'll
almost always be a QuerySet).</p>
<dl class="function">
<dt id="django.core.serializers.get_serializer">
<code class="descclassname">django.core.serializers.</code><code class="descname">get_serializer</code>(<em>format</em>)<a class="headerlink" href="#django.core.serializers.get_serializer" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>You can also use a serializer object directly:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">XMLSerializer</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">get_serializer</span><span class="p">(</span><span class="s2">&quot;xml&quot;</span><span class="p">)</span>
<span class="n">xml_serializer</span> <span class="o">=</span> <span class="n">XMLSerializer</span><span class="p">()</span>
<span class="n">xml_serializer</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="n">queryset</span><span class="p">)</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">xml_serializer</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>
</div>
<p>This is useful if you want to serialize data directly to a file-like object
(which includes an <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">HttpResponse</span></code></a>):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">&quot;file.xml&quot;</span><span class="p">,</span> <span class="s2">&quot;w&quot;</span><span class="p">)</span> <span class="k">as</span> <span class="n">out</span><span class="p">:</span>
    <span class="n">xml_serializer</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="n">stream</span><span class="o">=</span><span class="n">out</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Calling <a class="reference internal" href="#django.core.serializers.get_serializer" title="django.core.serializers.get_serializer"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_serializer()</span></code></a> with an unknown
<a class="reference internal" href="#serialization-formats"><span class="std std-ref">format</span></a> will raise a
<code class="docutils literal notranslate"><span class="pre">django.core.serializers.SerializerDoesNotExist</span></code> exception.</p>
</div>
<div class="section" id="s-subset-of-fields">
<span id="s-id1"></span><span id="subset-of-fields"></span><span id="id1"></span><h3>Subset of fields<a class="headerlink" href="#subset-of-fields" title="永久链接至标题">¶</a></h3>
<p>If you only want a subset of fields to be serialized, you can
specify a <code class="docutils literal notranslate"><span class="pre">fields</span></code> argument to the serializer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core</span> <span class="kn">import</span> <span class="n">serializers</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s1">&#39;xml&#39;</span><span class="p">,</span> <span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="n">fields</span><span class="o">=</span><span class="p">(</span><span class="s1">&#39;name&#39;</span><span class="p">,</span><span class="s1">&#39;size&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>In this example, only the <code class="docutils literal notranslate"><span class="pre">name</span></code> and <code class="docutils literal notranslate"><span class="pre">size</span></code> attributes of each model will
be serialized. The primary key is always serialized as the <code class="docutils literal notranslate"><span class="pre">pk</span></code> element in the
resulting output; it never appears in the <code class="docutils literal notranslate"><span class="pre">fields</span></code> part.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Depending on your model, you may find that it is not possible to
deserialize a model that only serializes a subset of its fields. If a
serialized object doesn't specify all the fields that are required by a
model, the deserializer will not be able to save deserialized instances.</p>
</div>
</div>
<div class="section" id="s-inherited-models">
<span id="inherited-models"></span><h3>Inherited models<a class="headerlink" href="#inherited-models" title="永久链接至标题">¶</a></h3>
<p>If you have a model that is defined using an <a class="reference internal" href="db/models.html#abstract-base-classes"><span class="std std-ref">abstract base class</span></a>, you don't have to do anything special to serialize
that model. Call the serializer on the object (or objects) that you want to
serialize, and the output will be a complete representation of the serialized
object.</p>
<p>However, if you have a model that uses <a class="reference internal" href="db/models.html#multi-table-inheritance"><span class="std std-ref">multi-table inheritance</span></a>, you also need to serialize all of the base classes
for the model. This is because only the fields that are locally defined on the
model will be serialized. For example, consider the following models:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Place</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Restaurant</span><span class="p">(</span><span class="n">Place</span><span class="p">):</span>
    <span class="n">serves_hot_dogs</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<p>If you only serialize the Restaurant model:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s1">&#39;xml&#39;</span><span class="p">,</span> <span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">())</span>
</pre></div>
</div>
<p>the fields on the serialized output will only contain the <code class="docutils literal notranslate"><span class="pre">serves_hot_dogs</span></code>
attribute. The <code class="docutils literal notranslate"><span class="pre">name</span></code> attribute of the base class will be ignored.</p>
<p>In order to fully serialize your <code class="docutils literal notranslate"><span class="pre">Restaurant</span></code> instances, you will need to
serialize the <code class="docutils literal notranslate"><span class="pre">Place</span></code> models as well:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">all_objects</span> <span class="o">=</span> <span class="p">[</span><span class="o">*</span><span class="n">Restaurant</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="o">*</span><span class="n">Place</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">()]</span>
<span class="n">data</span> <span class="o">=</span> <span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s1">&#39;xml&#39;</span><span class="p">,</span> <span class="n">all_objects</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="s-deserializing-data">
<span id="deserializing-data"></span><h2>Deserializing data<a class="headerlink" href="#deserializing-data" title="永久链接至标题">¶</a></h2>
<p>Deserializing data is very similar to serializing it:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s2">&quot;xml&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="n">do_something_with</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
</pre></div>
</div>
<p>As you can see, the <code class="docutils literal notranslate"><span class="pre">deserialize</span></code> function takes the same format argument as
<code class="docutils literal notranslate"><span class="pre">serialize</span></code>, a string or stream of data, and returns an iterator.</p>
<p>However, here it gets slightly complicated. The objects returned by the
<code class="docutils literal notranslate"><span class="pre">deserialize</span></code> iterator <em>aren't</em> regular Django objects. Instead, they are
special <code class="docutils literal notranslate"><span class="pre">DeserializedObject</span></code> instances that wrap a created -- but unsaved --
object and any associated relationship data.</p>
<p>Calling <code class="docutils literal notranslate"><span class="pre">DeserializedObject.save()</span></code> saves the object to the database.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">If the <code class="docutils literal notranslate"><span class="pre">pk</span></code> attribute in the serialized data doesn't exist or is
null, a new instance will be saved to the database.</p>
</div>
<p>This ensures that deserializing is a non-destructive operation even if the
data in your serialized representation doesn't match what's currently in the
database. Usually, working with these <code class="docutils literal notranslate"><span class="pre">DeserializedObject</span></code> instances looks
something like:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">deserialized_object</span> <span class="ow">in</span> <span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s2">&quot;xml&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="k">if</span> <span class="n">object_should_be_saved</span><span class="p">(</span><span class="n">deserialized_object</span><span class="p">):</span>
        <span class="n">deserialized_object</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
</pre></div>
</div>
<p>In other words, the usual use is to examine the deserialized objects to make
sure that they are &quot;appropriate&quot; for saving before doing so. If you trust your
data source you can instead save the object directly and move on.</p>
<p>The Django object itself can be inspected as <code class="docutils literal notranslate"><span class="pre">deserialized_object.object</span></code>.
If fields in the serialized data do not exist on a model, a
<code class="docutils literal notranslate"><span class="pre">DeserializationError</span></code> will be raised unless the <code class="docutils literal notranslate"><span class="pre">ignorenonexistent</span></code>
argument is passed in as <code class="docutils literal notranslate"><span class="pre">True</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s2">&quot;xml&quot;</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="n">ignorenonexistent</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="section" id="s-serialization-formats">
<span id="s-id2"></span><span id="serialization-formats"></span><span id="id2"></span><h2>Serialization formats<a class="headerlink" href="#serialization-formats" title="永久链接至标题">¶</a></h2>
<p>Django supports a number of serialization formats, some of which require you
to install third-party Python modules:</p>
<table class="docutils">
<colgroup>
<col width="14%" />
<col width="86%" />
</colgroup>
<thead valign="bottom">
<tr class="row-odd"><th class="head">Identifier</th>
<th class="head">Information</th>
</tr>
</thead>
<tbody valign="top">
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">xml</span></code></td>
<td>Serializes to and from a simple XML dialect.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">json</span></code></td>
<td>Serializes to and from <a class="reference external" href="https://json.org/">JSON</a>.</td>
</tr>
<tr class="row-even"><td><code class="docutils literal notranslate"><span class="pre">jsonl</span></code></td>
<td>Serializes to and from <a class="reference external" href="https://jsonlines.org/">JSONL</a>.</td>
</tr>
<tr class="row-odd"><td><code class="docutils literal notranslate"><span class="pre">yaml</span></code></td>
<td>Serializes to YAML (YAML Ain't a Markup Language). This
serializer is only available if <a class="reference external" href="https://pyyaml.org/">PyYAML</a> is installed.</td>
</tr>
</tbody>
</table>
<div class="section" id="s-xml">
<span id="xml"></span><h3>XML<a class="headerlink" href="#xml" title="永久链接至标题">¶</a></h3>
<p>The basic XML serialization format looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;django-objects version=&quot;1.0&quot;&gt;
    &lt;object pk=&quot;123&quot; model=&quot;sessions.session&quot;&gt;
        &lt;field type=&quot;DateTimeField&quot; name=&quot;expire_date&quot;&gt;2013-01-16T08:16:59.844560+00:00&lt;/field&gt;
        &lt;!-- ... --&gt;
    &lt;/object&gt;
&lt;/django-objects&gt;
</pre></div>
</div>
<p>The whole collection of objects that is either serialized or deserialized is
represented by a <code class="docutils literal notranslate"><span class="pre">&lt;django-objects&gt;</span></code>-tag which contains multiple
<code class="docutils literal notranslate"><span class="pre">&lt;object&gt;</span></code>-elements. Each such object has two attributes: &quot;pk&quot; and &quot;model&quot;,
the latter being represented by the name of the app (&quot;sessions&quot;) and the
lowercase name of the model (&quot;session&quot;) separated by a dot.</p>
<p>Each field of the object is serialized as a <code class="docutils literal notranslate"><span class="pre">&lt;field&gt;</span></code>-element sporting the
fields &quot;type&quot; and &quot;name&quot;. The text content of the element represents the value
that should be stored.</p>
<p>Foreign keys and other relational fields are treated a little bit differently:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>&lt;object pk=&quot;27&quot; model=&quot;auth.permission&quot;&gt;
    &lt;!-- ... --&gt;
    &lt;field to=&quot;contenttypes.contenttype&quot; name=&quot;content_type&quot; rel=&quot;ManyToOneRel&quot;&gt;9&lt;/field&gt;
    &lt;!-- ... --&gt;
&lt;/object&gt;
</pre></div>
</div>
<p>In this example we specify that the <code class="docutils literal notranslate"><span class="pre">auth.Permission</span></code> object with the PK 27
has a foreign key to the <code class="docutils literal notranslate"><span class="pre">contenttypes.ContentType</span></code> instance with the PK 9.</p>
<p>ManyToMany-relations are exported for the model that binds them. For instance,
the <code class="docutils literal notranslate"><span class="pre">auth.User</span></code> model has such a relation to the <code class="docutils literal notranslate"><span class="pre">auth.Permission</span></code> model:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>&lt;object pk=&quot;1&quot; model=&quot;auth.user&quot;&gt;
    &lt;!-- ... --&gt;
    &lt;field to=&quot;auth.permission&quot; name=&quot;user_permissions&quot; rel=&quot;ManyToManyRel&quot;&gt;
        &lt;object pk=&quot;46&quot;&gt;&lt;/object&gt;
        &lt;object pk=&quot;47&quot;&gt;&lt;/object&gt;
    &lt;/field&gt;
&lt;/object&gt;
</pre></div>
</div>
<p>This example links the given user with the permission models with PKs 46 and 47.</p>
<div class="admonition-control-characters admonition">
<p class="first admonition-title">Control characters</p>
<p class="last">If the content to be serialized contains control characters that are not
accepted in the XML 1.0 standard, the serialization will fail with a
<a class="reference external" href="https://docs.python.org/3/library/exceptions.html#ValueError" title="(在 Python v3.9)"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ValueError</span></code></a> exception. Read also the W3C's explanation of <a class="reference external" href="https://www.w3.org/International/questions/qa-controls">HTML,
XHTML, XML and Control Codes</a>.</p>
</div>
</div>
<div class="section" id="s-serialization-formats-json">
<span id="s-id3"></span><span id="serialization-formats-json"></span><span id="id3"></span><h3>JSON<a class="headerlink" href="#serialization-formats-json" title="永久链接至标题">¶</a></h3>
<p>When staying with the same example data as before it would be serialized as
JSON in the following way:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">[</span>
    <span class="p">{</span>
        <span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="s2">&quot;4b678b301dfd8a4e0dad910de3ae245b&quot;</span><span class="p">,</span>
        <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;sessions.session&quot;</span><span class="p">,</span>
        <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
            <span class="s2">&quot;expire_date&quot;</span><span class="p">:</span> <span class="s2">&quot;2013-01-16T08:16:59.844Z&quot;</span><span class="p">,</span>
            <span class="o">...</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">]</span>
</pre></div>
</div>
<p>The formatting here is a bit simpler than with XML. The whole collection
is just represented as an array and the objects are represented by JSON objects
with three properties: &quot;pk&quot;, &quot;model&quot; and &quot;fields&quot;. &quot;fields&quot; is again an object
containing each field's name and value as property and property-value
respectively.</p>
<p>Foreign keys have the PK of the linked object as property value.
ManyToMany-relations are serialized for the model that defines them and are
represented as a list of PKs.</p>
<p>Be aware that not all Django output can be passed unmodified to <a class="reference external" href="https://docs.python.org/3/library/json.html#module-json" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a>.
For example, if you have some custom type in an object to be serialized, you'll
have to write a custom <a class="reference external" href="https://docs.python.org/3/library/json.html#module-json" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> encoder for it. Something like this will
work:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.serializers.json</span> <span class="kn">import</span> <span class="n">DjangoJSONEncoder</span>

<span class="k">class</span> <span class="nc">LazyEncoder</span><span class="p">(</span><span class="n">DjangoJSONEncoder</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">default</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">obj</span><span class="p">):</span>
        <span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">YourCustomType</span><span class="p">):</span>
            <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
        <span class="k">return</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">default</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>
</pre></div>
</div>
<p>You can then pass <code class="docutils literal notranslate"><span class="pre">cls=LazyEncoder</span></code> to the <code class="docutils literal notranslate"><span class="pre">serializers.serialize()</span></code>
function:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.core.serializers</span> <span class="kn">import</span> <span class="n">serialize</span>

<span class="n">serialize</span><span class="p">(</span><span class="s1">&#39;json&#39;</span><span class="p">,</span> <span class="n">SomeModel</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">all</span><span class="p">(),</span> <span class="bp">cls</span><span class="o">=</span><span class="n">LazyEncoder</span><span class="p">)</span>
</pre></div>
</div>
<p>Also note that GeoDjango provides a <a class="reference internal" href="../ref/contrib/gis/serializers.html"><span class="doc">customized GeoJSON serializer</span></a>.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>All data is now dumped with Unicode. If you need the previous behavior,
pass <code class="docutils literal notranslate"><span class="pre">ensure_ascii=True</span></code> to the <code class="docutils literal notranslate"><span class="pre">serializers.serialize()</span></code> function.</p>
</div>
<div class="section" id="s-djangojsonencoder">
<span id="djangojsonencoder"></span><h4><code class="docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code><a class="headerlink" href="#djangojsonencoder" title="永久链接至标题">¶</a></h4>
<dl class="class">
<dt id="django.core.serializers.json.DjangoJSONEncoder">
<em class="property">class </em><code class="descclassname">django.core.serializers.json.</code><code class="descname">DjangoJSONEncoder</code><a class="headerlink" href="#django.core.serializers.json.DjangoJSONEncoder" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>The JSON serializer uses <code class="docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code> for encoding. A subclass of
<a class="reference external" href="https://docs.python.org/3/library/json.html#json.JSONEncoder" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">JSONEncoder</span></code></a>, it handles these additional types:</p>
<dl class="docutils">
<dt><a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.datetime" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">datetime</span></code></a></dt>
<dd>A string of the form <code class="docutils literal notranslate"><span class="pre">YYYY-MM-DDTHH:mm:ss.sssZ</span></code> or
<code class="docutils literal notranslate"><span class="pre">YYYY-MM-DDTHH:mm:ss.sss+HH:MM</span></code> as defined in <a class="reference external" href="https://262.ecma-international.org/5.1/#sec-15.9.1.15">ECMA-262</a>.</dd>
<dt><a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.date" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">date</span></code></a></dt>
<dd>A string of the form <code class="docutils literal notranslate"><span class="pre">YYYY-MM-DD</span></code> as defined in <a class="reference external" href="https://262.ecma-international.org/5.1/#sec-15.9.1.15">ECMA-262</a>.</dd>
<dt><a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.time" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">time</span></code></a></dt>
<dd>A string of the form <code class="docutils literal notranslate"><span class="pre">HH:MM:ss.sss</span></code> as defined in <a class="reference external" href="https://262.ecma-international.org/5.1/#sec-15.9.1.15">ECMA-262</a>.</dd>
<dt><a class="reference external" href="https://docs.python.org/3/library/datetime.html#datetime.timedelta" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">timedelta</span></code></a></dt>
<dd>A string representing a duration as defined in ISO-8601. For example,
<code class="docutils literal notranslate"><span class="pre">timedelta(days=1,</span> <span class="pre">hours=2,</span> <span class="pre">seconds=3.4)</span></code> is represented as
<code class="docutils literal notranslate"><span class="pre">'P1DT02H00M03.400000S'</span></code>.</dd>
<dt><a class="reference external" href="https://docs.python.org/3/library/decimal.html#decimal.Decimal" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a>, <code class="docutils literal notranslate"><span class="pre">Promise</span></code> (<code class="docutils literal notranslate"><span class="pre">django.utils.functional.lazy()</span></code> objects), <a class="reference external" href="https://docs.python.org/3/library/uuid.html#uuid.UUID" title="(在 Python v3.9)"><code class="xref py py-class docutils literal notranslate"><span class="pre">UUID</span></code></a></dt>
<dd>A string representation of the object.</dd>
</dl>
</div>
</div>
<div class="section" id="s-serialization-formats-jsonl">
<span id="s-id4"></span><span id="serialization-formats-jsonl"></span><span id="id4"></span><h3>JSONL<a class="headerlink" href="#serialization-formats-jsonl" title="永久链接至标题">¶</a></h3>
<div class="versionadded">
<span class="title">New in Django 3.2.</span> </div>
<p><em>JSONL</em> stands for <em>JSON Lines</em>. With this format, objects are separated by new
lines, and each line contains a valid JSON object. JSONL serialized data looks
like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="p">{</span><span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="s2">&quot;4b678b301dfd8a4e0dad910de3ae245b&quot;</span><span class="p">,</span> <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;sessions.session&quot;</span><span class="p">,</span> <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span><span class="o">...</span><span class="p">}}</span>
<span class="p">{</span><span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="s2">&quot;88bea72c02274f3c9bf1cb2bb8cee4fc&quot;</span><span class="p">,</span> <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;sessions.session&quot;</span><span class="p">,</span> <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span><span class="o">...</span><span class="p">}}</span>
<span class="p">{</span><span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="s2">&quot;9cf0e26691b64147a67e2a9f06ad7a53&quot;</span><span class="p">,</span> <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;sessions.session&quot;</span><span class="p">,</span> <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span><span class="o">...</span><span class="p">}}</span>
</pre></div>
</div>
<p>JSONL can be useful for populating large databases, since the data can be
processed line by line, rather than being loaded into memory all at once.</p>
</div>
<div class="section" id="s-yaml">
<span id="yaml"></span><h3>YAML<a class="headerlink" href="#yaml" title="永久链接至标题">¶</a></h3>
<p>YAML serialization looks quite similar to JSON. The object list is serialized
as a sequence mappings with the keys &quot;pk&quot;, &quot;model&quot; and &quot;fields&quot;. Each field is
again a mapping with the key being name of the field and the value the value:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span>-   fields: {expire_date: !!timestamp &#39;2013-01-16 08:16:59.844560+00:00&#39;}
    model: sessions.session
    pk: 4b678b301dfd8a4e0dad910de3ae245b
</pre></div>
</div>
<p>Referential fields are again represented by the PK or sequence of PKs.</p>
<div class="versionchanged">
<span class="title">Changed in Django 3.1:</span> <p>All data is now dumped with Unicode. If you need the previous behavior,
pass <code class="docutils literal notranslate"><span class="pre">allow_unicode=False</span></code> to the <code class="docutils literal notranslate"><span class="pre">serializers.serialize()</span></code> function.</p>
</div>
</div>
</div>
<div class="section" id="s-natural-keys">
<span id="s-topics-serialization-natural-keys"></span><span id="natural-keys"></span><span id="topics-serialization-natural-keys"></span><h2>Natural keys<a class="headerlink" href="#natural-keys" title="永久链接至标题">¶</a></h2>
<p>The default serialization strategy for foreign keys and many-to-many relations
is to serialize the value of the primary key(s) of the objects in the relation.
This strategy works well for most objects, but it can cause difficulty in some
circumstances.</p>
<p>Consider the case of a list of objects that have a foreign key referencing
<a class="reference internal" href="../ref/contrib/contenttypes.html#django.contrib.contenttypes.models.ContentType" title="django.contrib.contenttypes.models.ContentType"><code class="xref py py-class docutils literal notranslate"><span class="pre">ContentType</span></code></a>. If you're going to
serialize an object that refers to a content type, then you need to have a way
to refer to that content type to begin with. Since <code class="docutils literal notranslate"><span class="pre">ContentType</span></code> objects are
automatically created by Django during the database synchronization process,
the primary key of a given content type isn't easy to predict; it will
depend on how and when <a class="reference internal" href="../ref/django-admin.html#django-admin-migrate"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">migrate</span></code></a> was executed. This is true for all
models which automatically generate objects, notably including
<a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.models.Permission" title="django.contrib.auth.models.Permission"><code class="xref py py-class docutils literal notranslate"><span class="pre">Permission</span></code></a>,
<a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.models.Group" title="django.contrib.auth.models.Group"><code class="xref py py-class docutils literal notranslate"><span class="pre">Group</span></code></a>, and
<a class="reference internal" href="../ref/contrib/auth.html#django.contrib.auth.models.User" title="django.contrib.auth.models.User"><code class="xref py py-class docutils literal notranslate"><span class="pre">User</span></code></a>.</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">You should never include automatically generated objects in a fixture or
other serialized data. By chance, the primary keys in the fixture
may match those in the database and loading the fixture will
have no effect. In the more likely case that they don't match, the fixture
loading will fail with an <a class="reference internal" href="../ref/exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-class docutils literal notranslate"><span class="pre">IntegrityError</span></code></a>.</p>
</div>
<p>There is also the matter of convenience. An integer id isn't always
the most convenient way to refer to an object; sometimes, a
more natural reference would be helpful.</p>
<p>It is for these reasons that Django provides <em>natural keys</em>. A natural
key is a tuple of values that can be used to uniquely identify an
object instance without using the primary key value.</p>
<div class="section" id="s-deserialization-of-natural-keys">
<span id="deserialization-of-natural-keys"></span><h3>Deserialization of natural keys<a class="headerlink" href="#deserialization-of-natural-keys" title="永久链接至标题">¶</a></h3>
<p>Consider the following two models:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>

    <span class="n">birthdate</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;first_name&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">]]</span>

<span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>
</pre></div>
</div>
<p>Ordinarily, serialized data for <code class="docutils literal notranslate"><span class="pre">Book</span></code> would use an integer to refer to
the author. For example, in JSON, a Book might be serialized as:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="p">{</span>
    <span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;store.book&quot;</span><span class="p">,</span>
    <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s2">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;Mostly Harmless&quot;</span><span class="p">,</span>
        <span class="s2">&quot;author&quot;</span><span class="p">:</span> <span class="mi">42</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This isn't a particularly natural way to refer to an author. It
requires that you know the primary key value for the author; it also
requires that this primary key value is stable and predictable.</p>
<p>However, if we add natural key handling to Person, the fixture becomes
much more humane. To add natural key handling, you define a default
Manager for Person with a <code class="docutils literal notranslate"><span class="pre">get_by_natural_key()</span></code> method. In the case
of a Person, a good natural key might be the pair of first and last
name:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span>

<span class="k">class</span> <span class="nc">PersonManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span>
    <span class="k">def</span> <span class="nf">get_by_natural_key</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span><span class="p">):</span>
        <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">first_name</span><span class="o">=</span><span class="n">first_name</span><span class="p">,</span> <span class="n">last_name</span><span class="o">=</span><span class="n">last_name</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">birthdate</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

    <span class="n">objects</span> <span class="o">=</span> <span class="n">PersonManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;first_name&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">]]</span>
</pre></div>
</div>
<p>Now books can use that natural key to refer to <code class="docutils literal notranslate"><span class="pre">Person</span></code> objects:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="p">{</span>
    <span class="s2">&quot;pk&quot;</span><span class="p">:</span> <span class="mi">1</span><span class="p">,</span>
    <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;store.book&quot;</span><span class="p">,</span>
    <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s2">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;Mostly Harmless&quot;</span><span class="p">,</span>
        <span class="s2">&quot;author&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Douglas&quot;</span><span class="p">,</span> <span class="s2">&quot;Adams&quot;</span><span class="p">]</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="o">...</span>
</pre></div>
</div>
<p>When you try to load this serialized data, Django will use the
<code class="docutils literal notranslate"><span class="pre">get_by_natural_key()</span></code> method to resolve <code class="docutils literal notranslate"><span class="pre">[&quot;Douglas&quot;,</span> <span class="pre">&quot;Adams&quot;]</span></code>
into the primary key of an actual <code class="docutils literal notranslate"><span class="pre">Person</span></code> object.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">Whatever fields you use for a natural key must be able to uniquely
identify an object. This will usually mean that your model will
have a uniqueness clause (either unique=True on a single field, or
<code class="docutils literal notranslate"><span class="pre">unique_together</span></code> over multiple fields) for the field or fields
in your natural key. However, uniqueness doesn't need to be
enforced at the database level. If you are certain that a set of
fields will be effectively unique, you can still use those fields
as a natural key.</p>
</div>
<p>Deserialization of objects with no primary key will always check whether the
model's manager has a <code class="docutils literal notranslate"><span class="pre">get_by_natural_key()</span></code> method and if so, use it to
populate the deserialized object's primary key.</p>
</div>
<div class="section" id="s-serialization-of-natural-keys">
<span id="serialization-of-natural-keys"></span><h3>Serialization of natural keys<a class="headerlink" href="#serialization-of-natural-keys" title="永久链接至标题">¶</a></h3>
<p>So how do you get Django to emit a natural key when serializing an object?
Firstly, you need to add another method -- this time to the model itself:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Person</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">first_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">last_name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">birthdate</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateField</span><span class="p">()</span>

    <span class="n">objects</span> <span class="o">=</span> <span class="n">PersonManager</span><span class="p">()</span>

    <span class="k">class</span> <span class="nc">Meta</span><span class="p">:</span>
        <span class="n">unique_together</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;first_name&#39;</span><span class="p">,</span> <span class="s1">&#39;last_name&#39;</span><span class="p">]]</span>

    <span class="k">def</span> <span class="nf">natural_key</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">first_name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">last_name</span><span class="p">)</span>
</pre></div>
</div>
<p>That method should always return a natural key tuple -- in this
example, <code class="docutils literal notranslate"><span class="pre">(first</span> <span class="pre">name,</span> <span class="pre">last</span> <span class="pre">name)</span></code>. Then, when you call
<code class="docutils literal notranslate"><span class="pre">serializers.serialize()</span></code>, you provide <code class="docutils literal notranslate"><span class="pre">use_natural_foreign_keys=True</span></code>
or <code class="docutils literal notranslate"><span class="pre">use_natural_primary_keys=True</span></code> arguments:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">serializers</span><span class="o">.</span><span class="n">serialize</span><span class="p">(</span><span class="s1">&#39;json&#39;</span><span class="p">,</span> <span class="p">[</span><span class="n">book1</span><span class="p">,</span> <span class="n">book2</span><span class="p">],</span> <span class="n">indent</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span>
<span class="gp">... </span>     <span class="n">use_natural_foreign_keys</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">use_natural_primary_keys</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
</pre></div>
</div>
<p>When <code class="docutils literal notranslate"><span class="pre">use_natural_foreign_keys=True</span></code> is specified, Django will use the
<code class="docutils literal notranslate"><span class="pre">natural_key()</span></code> method to serialize any foreign key reference to objects
of the type that defines the method.</p>
<p>When <code class="docutils literal notranslate"><span class="pre">use_natural_primary_keys=True</span></code> is specified, Django will not provide the
primary key in the serialized data of this object since it can be calculated
during deserialization:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="p">{</span>
    <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;store.person&quot;</span><span class="p">,</span>
    <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s2">&quot;first_name&quot;</span><span class="p">:</span> <span class="s2">&quot;Douglas&quot;</span><span class="p">,</span>
        <span class="s2">&quot;last_name&quot;</span><span class="p">:</span> <span class="s2">&quot;Adams&quot;</span><span class="p">,</span>
        <span class="s2">&quot;birth_date&quot;</span><span class="p">:</span> <span class="s2">&quot;1952-03-11&quot;</span><span class="p">,</span>
    <span class="p">}</span>
<span class="p">}</span>
<span class="o">...</span>
</pre></div>
</div>
<p>This can be useful when you need to load serialized data into an existing
database and you cannot guarantee that the serialized primary key value is not
already in use, and do not need to ensure that deserialized objects retain the
same primary keys.</p>
<p>If you are using <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">dumpdata</span></code></a> to generate serialized data, use the
<a class="reference internal" href="../ref/django-admin.html#cmdoption-dumpdata-natural-foreign"><code class="xref std std-option docutils literal notranslate"><span class="pre">dumpdata</span> <span class="pre">--natural-foreign</span></code></a> and <a class="reference internal" href="../ref/django-admin.html#cmdoption-dumpdata-natural-primary"><code class="xref std std-option docutils literal notranslate"><span class="pre">dumpdata</span> <span class="pre">--natural-primary</span></code></a>
command line flags to generate natural keys.</p>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p>You don't need to define both <code class="docutils literal notranslate"><span class="pre">natural_key()</span></code> and
<code class="docutils literal notranslate"><span class="pre">get_by_natural_key()</span></code>. If you don't want Django to output
natural keys during serialization, but you want to retain the
ability to load natural keys, then you can opt to not implement
the <code class="docutils literal notranslate"><span class="pre">natural_key()</span></code> method.</p>
<p class="last">Conversely, if (for some strange reason) you want Django to output
natural keys during serialization, but <em>not</em> be able to load those
key values, just don't define the <code class="docutils literal notranslate"><span class="pre">get_by_natural_key()</span></code> method.</p>
</div>
</div>
<div class="section" id="s-natural-keys-and-forward-references">
<span id="s-id5"></span><span id="natural-keys-and-forward-references"></span><span id="id5"></span><h3>Natural keys and forward references<a class="headerlink" href="#natural-keys-and-forward-references" title="永久链接至标题">¶</a></h3>
<p>Sometimes when you use <a class="reference internal" href="#topics-serialization-natural-keys"><span class="std std-ref">natural foreign keys</span></a> you'll need to deserialize data where
an object has a foreign key referencing another object that hasn't yet been
deserialized. This is called a &quot;forward reference&quot;.</p>
<p>For instance, suppose you have the following objects in your fixture:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="o">...</span>
<span class="p">{</span>
    <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;store.book&quot;</span><span class="p">,</span>
    <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s2">&quot;name&quot;</span><span class="p">:</span> <span class="s2">&quot;Mostly Harmless&quot;</span><span class="p">,</span>
        <span class="s2">&quot;author&quot;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Douglas&quot;</span><span class="p">,</span> <span class="s2">&quot;Adams&quot;</span><span class="p">]</span>
    <span class="p">}</span>
<span class="p">},</span>
<span class="o">...</span>
<span class="p">{</span>
    <span class="s2">&quot;model&quot;</span><span class="p">:</span> <span class="s2">&quot;store.person&quot;</span><span class="p">,</span>
    <span class="s2">&quot;fields&quot;</span><span class="p">:</span> <span class="p">{</span>
        <span class="s2">&quot;first_name&quot;</span><span class="p">:</span> <span class="s2">&quot;Douglas&quot;</span><span class="p">,</span>
        <span class="s2">&quot;last_name&quot;</span><span class="p">:</span> <span class="s2">&quot;Adams&quot;</span>
    <span class="p">}</span>
<span class="p">},</span>
<span class="o">...</span>
</pre></div>
</div>
<p>In order to handle this situation, you need to pass
<code class="docutils literal notranslate"><span class="pre">handle_forward_references=True</span></code> to <code class="docutils literal notranslate"><span class="pre">serializers.deserialize()</span></code>. This will
set the <code class="docutils literal notranslate"><span class="pre">deferred_fields</span></code> attribute on the <code class="docutils literal notranslate"><span class="pre">DeserializedObject</span></code> instances.
You'll need to keep track of <code class="docutils literal notranslate"><span class="pre">DeserializedObject</span></code> instances where this
attribute isn't <code class="docutils literal notranslate"><span class="pre">None</span></code> and later call <code class="docutils literal notranslate"><span class="pre">save_deferred_fields()</span></code> on them.</p>
<p>Typical usage looks like this:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">objs_with_deferred_fields</span> <span class="o">=</span> <span class="p">[]</span>

<span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">serializers</span><span class="o">.</span><span class="n">deserialize</span><span class="p">(</span><span class="s1">&#39;xml&#39;</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="n">handle_forward_references</span><span class="o">=</span><span class="kc">True</span><span class="p">):</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="k">if</span> <span class="n">obj</span><span class="o">.</span><span class="n">deferred_fields</span> <span class="ow">is</span> <span class="ow">not</span> <span class="kc">None</span><span class="p">:</span>
        <span class="n">objs_with_deferred_fields</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span>

<span class="k">for</span> <span class="n">obj</span> <span class="ow">in</span> <span class="n">objs_with_deferred_fields</span><span class="p">:</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">save_deferred_fields</span><span class="p">()</span>
</pre></div>
</div>
<p>For this to work, the <code class="docutils literal notranslate"><span class="pre">ForeignKey</span></code> on the referencing model must have
<code class="docutils literal notranslate"><span class="pre">null=True</span></code>.</p>
</div>
<div class="section" id="s-dependencies-during-serialization">
<span id="dependencies-during-serialization"></span><h3>Dependencies during serialization<a class="headerlink" href="#dependencies-during-serialization" title="永久链接至标题">¶</a></h3>
<p>It's often possible to avoid explicitly having to handle forward references by
taking care with the ordering of objects within a fixture.</p>
<p>To help with this, calls to <a class="reference internal" href="../ref/django-admin.html#django-admin-dumpdata"><code class="xref std std-djadmin docutils literal notranslate"><span class="pre">dumpdata</span></code></a> that use the <a class="reference internal" href="../ref/django-admin.html#cmdoption-dumpdata-natural-foreign"><code class="xref std std-option docutils literal notranslate"><span class="pre">dumpdata</span>
<span class="pre">--natural-foreign</span></code></a> option will serialize any model with a <code class="docutils literal notranslate"><span class="pre">natural_key()</span></code>
method before serializing standard primary key objects.</p>
<p>However, this may not always be enough. If your natural key refers to
another object (by using a foreign key or natural key to another object
as part of a natural key), then you need to be able to ensure that
the objects on which a natural key depends occur in the serialized data
before the natural key requires them.</p>
<p>To control this ordering, you can define dependencies on your
<code class="docutils literal notranslate"><span class="pre">natural_key()</span></code> methods. You do this by setting a <code class="docutils literal notranslate"><span class="pre">dependencies</span></code>
attribute on the <code class="docutils literal notranslate"><span class="pre">natural_key()</span></code> method itself.</p>
<p>For example, let's add a natural key to the <code class="docutils literal notranslate"><span class="pre">Book</span></code> model from the
example above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Book</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span>
    <span class="n">name</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">100</span><span class="p">)</span>
    <span class="n">author</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Person</span><span class="p">,</span> <span class="n">on_delete</span><span class="o">=</span><span class="n">models</span><span class="o">.</span><span class="n">CASCADE</span><span class="p">)</span>

    <span class="k">def</span> <span class="nf">natural_key</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">author</span><span class="o">.</span><span class="n">natural_key</span><span class="p">()</span>
</pre></div>
</div>
<p>The natural key for a <code class="docutils literal notranslate"><span class="pre">Book</span></code> is a combination of its name and its
author. This means that <code class="docutils literal notranslate"><span class="pre">Person</span></code> must be serialized before <code class="docutils literal notranslate"><span class="pre">Book</span></code>.
To define this dependency, we add one extra line:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="nf">natural_key</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,)</span> <span class="o">+</span> <span class="bp">self</span><span class="o">.</span><span class="n">author</span><span class="o">.</span><span class="n">natural_key</span><span class="p">()</span>
<span class="n">natural_key</span><span class="o">.</span><span class="n">dependencies</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;example_app.person&#39;</span><span class="p">]</span>
</pre></div>
</div>
<p>This definition ensures that all <code class="docutils literal notranslate"><span class="pre">Person</span></code> objects are serialized before
any <code class="docutils literal notranslate"><span class="pre">Book</span></code> objects. In turn, any object referencing <code class="docutils literal notranslate"><span class="pre">Book</span></code> will be
serialized after both <code class="docutils literal notranslate"><span class="pre">Person</span></code> and <code class="docutils literal notranslate"><span class="pre">Book</span></code> have been serialized.</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Serializing Django objects</a><ul>
<li><a class="reference internal" href="#serializing-data">Serializing data</a><ul>
<li><a class="reference internal" href="#subset-of-fields">Subset of fields</a></li>
<li><a class="reference internal" href="#inherited-models">Inherited models</a></li>
</ul>
</li>
<li><a class="reference internal" href="#deserializing-data">Deserializing data</a></li>
<li><a class="reference internal" href="#serialization-formats">Serialization formats</a><ul>
<li><a class="reference internal" href="#xml">XML</a></li>
<li><a class="reference internal" href="#serialization-formats-json">JSON</a><ul>
<li><a class="reference internal" href="#djangojsonencoder"><code class="docutils literal notranslate"><span class="pre">DjangoJSONEncoder</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#serialization-formats-jsonl">JSONL</a></li>
<li><a class="reference internal" href="#yaml">YAML</a></li>
</ul>
</li>
<li><a class="reference internal" href="#natural-keys">Natural keys</a><ul>
<li><a class="reference internal" href="#deserialization-of-natural-keys">Deserialization of natural keys</a></li>
<li><a class="reference internal" href="#serialization-of-natural-keys">Serialization of natural keys</a></li>
<li><a class="reference internal" href="#natural-keys-and-forward-references">Natural keys and forward references</a></li>
<li><a class="reference internal" href="#dependencies-during-serialization">Dependencies during serialization</a></li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="performance.html"
                        title="上一章">Performance and optimization</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="settings.html"
                        title="下一章">Django settings</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/topics/serialization.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="performance.html" title="Performance and optimization">previous</a>
     |
    <a href="index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="settings.html" title="Django settings">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>